import { audioToken } from "@/api/produceOrder.js";
import { getToken } from "@/utils/auth";

const audioTeam = [];
let audioStartSwitch = false;
const getAudioUrl = "https://tsn.baidu.com/text2audio";
/**
 * 浏览器调用语音合成接口
 * 请参考 https://ai.baidu.com/docs#/TTS-API/41ac79a6
 * 强烈建议后端访问接口获取token返回给前端
 * client_id = API Key & client_secret = secret Key
 * 获取token接口: https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=uFYiXWMCiYvx68V4EVyCGeL8j4GAzXD5&client_secret=897Mm2qCj7bC1eHYVDxaWrO38FscTOHD
 */

function getBDVoicToken() {
  // 后端获取token
  return audioToken({
    grant_type: "client_credentials",
    client_id: "rm4gM15TyEBDYXtgw5C1WknK",
    client_secret: "LiChCRz4OYjk61NrphkzOC3Tl7bmQRBT",
  });
}

// Voice({
//   //语音合成
//   voiceSet: {
//     tex: "文字",
//   },
//   audioSet: {
//     volume: 1,
//     obeyMuteSwitch: false,
//   },
//   audioCallback: {
//     onPlay: () => {
//       console.log("音频开始播放了");
//     },
//   },
//   lineUp: true, // 加入语音队列
//   returnAudio: false, // 返回音频对象
// });

export default function openVoice(objs) {
  // 传入需转为语音的文本内容
  let lineUp = false;
  let returnAudio = false;
  if (typeof objs !== "string") {
    if (objs && objs.lineUp === true) {
      lineUp = true;
    }
    if (objs && objs.returnAudio === true) {
      returnAudio = true;
    }
  }
  if (returnAudio) {
    return new Promise((resolve, reject) => {
      openVoiceFc(objs, returnAudio)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  if ((lineUp = true)) {
    audioTeam.push(objs);
  }
  console.log(audioTeam);
  if (!audioStartSwitch) {
    audioStartSwitch = true;
    openVoiceFc(objs);
  }
}

function openVoiceFc(objs, returnAudio) {
  if (returnAudio) {
    return new Promise((resolve, reject) => {
      getBDVoicToken()
        .then((res) => {
          res.data = JSON.parse(res.data);
          if (res.data && res.data.access_token) {
            resolve(tts(objs, res.data.access_token, returnAudio));
          } else {
            reject("获取语音tok接口为空");
          }
        })
        .catch((err) => {
          reject(err || "获取语音tok接口失败");
        });
    });
  } else {
    getBDVoicToken()
      .then((res) => {
        res.data = JSON.parse(res.data);
        if (res.data && res.data.access_token) {
          console.log("token: " + res.data.access_token);
          tts(objs, res.data.access_token);
        } else {
          console.log("获取语音tok接口为空");
        }
      })
      .catch((err) => {
        console.log("获取语音tok接口失败", err);
      });
  }
}

function tts(objs, tok, returnAudio) {
  if (typeof objs == "string")
    objs = {
      voiceSet: {
        tex: objs,
      },
    };
  const data = {
    tok,
    cuid: "ErjBFSv4x8qInHXjWBu5wVs0lprJL8YA",
    ctp: 1,
    lan: "zh",
    per: 0,
    ...objs.voiceSet,
  };
  if (returnAudio) return btts(data, objs.audioSet, objs.audioCallback, objs.lineUp, returnAudio);
  btts(data, objs.audioSet, objs.audioCallback, objs.lineUp, returnAudio);
}

function btts(param, options, audioCallback, lineUp, returnAudio) {
  // if (returnAudio) return;
  const data = {
    tex: encodeURIComponent(encodeURIComponent(param.tex)),
    ...param,
  };
  // 使用 Fetch API 来接收和处理这个数据流
  fetch(`${process.env.VUE_APP_BASE_API}send/textToAudio`, {
    method: "POST",
    headers: {
      Authorization: "Bearer " + getToken(),
      ["Content-Type"]: "application/json",
    },
    body: JSON.stringify(data),
  })
    .then((response) => {
      console.log(response, "response");
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.arrayBuffer(); // 接收 MP3 数据流
    })
    .then((arrayBuffer) => {
      console.log(arrayBuffer, "arrayBuffer");
      const blob = new Blob([arrayBuffer], { type: "audio/mp3" }); // 创建 Blob 对象
      const audioURL = URL.createObjectURL(blob); // 创建音频 URL
      const audio = new Audio(audioURL); // 创建 Audio 对象

      audio.addEventListener("ended", function () {
        // 监听播放完成事件
        console.log("Audio finished playing");
        URL.revokeObjectURL(audioURL); // 释放资源
      });

      const targetElement = document.createElement("div");

      // 点击事件执行函数
      targetElement.addEventListener("click", () => {
        // 播放音频
        if (typeof audioCallback === "function") {
          audio.addEventListener("canplaythrough", () => {
            audioCallback(audio);
            audio.play();
          });
        } else {
          audio.play();
        }
      });
      // 触发点击事件（在适当的时机）
      targetElement.click();
    })
    // 捕获错误
    .catch((error) => {
      console.error("Error fetching and processing audio:", error);
    });
}
